package com.zm.xdata.service.publics.poster.util;


import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeMap;

/**
 * @description:
 * @author: YuXD
 * @create: 2018-12-03 11:10
 **/
public class MD5Utils {

    public static final String FIELD_SIGN = "sign";

    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 is unsupported", e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MessageDigest不支持MD5Util", e);
        }
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) {
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }


    /**
     * md5签名
     * <p>
     * 按参数名称升序，将参数值进行连接 签名
     *
     * @param appSecret
     * @param params
     * @return
     */
    public static String sign(String appSecret, TreeMap<String, String> params) {
        Set<String> keySet = params.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(FIELD_SIGN)) {
                continue;
            }
            if (params.get(k).trim().length() > 0) {
                // 参数值为空，则不参与签名
                sb.append(k).append("=").append(params.get(k).trim()).append("&");
            }
        }
        sb.append("key=").append(appSecret);
        return md5(sb.toString()).toUpperCase();
    }

//    /**
//     * 请求参数签名验证
//     *
//     * @param appSecret
//     * @param request
//     * @return true 验证通过 false 验证失败
//     * @throws Exception
//     */
//    public static boolean verifySign(String appSecret, HttpServletRequest request) throws Exception {
//        TreeMap<String, String> params = new TreeMap<String, String>();
//
//        String signStr = request.getParameter("sign");
//        if (StringUtil.isEmpty(signStr)) {
//            return true;
//            //throw new RuntimeException("There is no signature field in the request parameter!");
//        }
//
//        Enumeration<String> enu = request.getParameterNames();
//        while (enu.hasMoreElements()) {
//            String paramName = enu.nextElement().trim();
//            if (!paramName.equals("sign")) {
//                params.put(paramName, URLDecoder.decode(request.getParameter(paramName), "UTF-8"));
//            }
//        }
//
//        if (!sign(appSecret, params).equals(signStr)) {
//            return false;
//        }
//        return true;
//    }

    public static void main(String[] args) {

        TreeMap<String, String> params = new TreeMap<>();
        params.put("num", "2");
        params.put("skuid", "126");
        System.out.println(sign("RYkGUJHwqSQZqxxqki5RkrU9B8l5AxAY", params));


    }

}
